package com.situ.mall.controller.back;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.entity.User;
import com.situ.mall.service.IUserService;



@Controller
@RequestMapping("/user")
public class UserController{
	
	@Autowired
	private IUserService userService;
	
	
	@RequestMapping("/logout")
	private String logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("loginServlet.logout()");

		return "login";
		
		
	}
	@RequestMapping("/login")
	@ResponseBody
	private ServerResponse login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String checkCode = req.getParameter("checkCode");
		String checkCodeSession = (String)req.getSession().getAttribute("checkCodeSession");
		if("" == checkCode || null == checkCode || checkCode.equals(checkCodeSession) == false) {
			ServerResponse serverResponse = ServerResponse.createError("验证码错误");
//			JSONUtil.obj2Json(resp,serverResponse);
			return serverResponse;
		}
		
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		User user = userService.login(name,password);
		
		if(null != user) {// 登录成功
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			
			List<User>onlineUserList = (List<User>) session.getAttribute("onlineUserList");
			// 第一个用户登录时候这个list是null
			if(null == onlineUserList) {
				onlineUserList = new ArrayList<User>();
				session.setAttribute("onlineUserList", onlineUserList);
			}
			onlineUserList.add(user);
			
			ServerResponse serverResponse = ServerResponse.createSuccess("登录成功");
//			JSONUtil.obj2Json(resp, serverResponse);
			return serverResponse;
		}else {
			ServerResponse serverResponse = ServerResponse.createError("用户名或密码错误");
//			JSONUtil.obj2Json(resp, serverResponse);
			return serverResponse;
		}
		
	}
}
